import CryptoJS from 'crypto-js'
import { JsEncryptSingleton } from '@/utils/jsencryptSingleton'

/**
 * 随机生成AESKey
 * @param length 生成长度
 */
export function getAESKey(length: number): string {
  let result = ''
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length))
  }
  return result
}

/**
 * 加密
 * @param data 需要加密的数据
 * @param k 密钥
 */
export function encryptToBase64(data: string, k: string): string {
  const key = CryptoJS.enc.Utf8.parse(k)
  return CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(data), key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString()
}

export function decrypt(encryptedBase64String: string, k: string) {
  const key = CryptoJS.enc.Utf8.parse(k)
  // 解码 Base64 字符串
  const ciphertext = CryptoJS.enc.Base64.parse(encryptedBase64String)
  // 解密数据
  const decrypted = CryptoJS.AES.decrypt(
    {
      ciphertext: ciphertext
    } as any,
    key,
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }
  )
  // 转换为 Utf8 字符串\
  return decrypted.toString(CryptoJS.enc.Utf8)
}

/**
 * RSA使用公钥加密
 * @param data
 */
export function encryptByPublicKey(data: string): string {
  const encryptInstance = JsEncryptSingleton.getEncryptInstance(import.meta.env.VITE_APP_AES_KEY)
  return encryptInstance.encrypt(data) as string
}

export function base64ToHex(base64: string) {
  // 将 Base64 字符串解码为二进制字符串
  const binaryString = window.atob(base64)
  // 使用 Uint8Array 和 map 函数将每个字符的字符编码转换为十六进制，并连接为字符串
  return Array.from(binaryString)
    .map((char) => char.charCodeAt(0).toString(16).padStart(2, '0'))
    .join('')
}
